import { is } from '@electron-toolkit/utils'
import { BrowserWindow, BrowserWindowConstructorOptions, shell } from 'electron'
import { join } from 'node:path'
import url from 'node:url'
import icon from '../../resources/icon.png?asset'

export interface OptionsType extends Partial<BrowserWindowConstructorOptions> {
  openDevTool?: boolean
  hash?: string
  initShow?: boolean
}

export function createWindow(option: OptionsType): BrowserWindow {
  const win = new BrowserWindow(
    Object.assign(
      {
        width: 500,
        height: 350,
        show: false,
        autoHideMenuBar: true,
        frame: false,
        transparent: true,
        // alwaysOnTop: true,
        ...(process.platform === 'linux' ? { icon } : {}),
        webPreferences: {
          preload: join(__dirname, '../preload/index.js'),
          sandbox: false,
        },
      },
      option,
    ),
  )
  if (is.dev && option.openDevTool) {
    win.webContents.openDevTools()
  }
  win.on('ready-to-show', () => {
    option.initShow && win.show()
  })
  // 拦截window.open打开的链接，使用外部浏览器打开
  win.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    win.loadURL(process.env['ELECTRON_RENDERER_URL'] + option.hash)
  } else {
    win.loadURL(
      url.format({
        // 编译后文件
        pathname: join(__dirname, '../renderer/index.html'),
        // 协议
        protocol: 'file',
        // protocol 后面需要两个//,
        slashes: true,
        // hash的值
        hash: option.hash?.substring(1),
      }),
    )
  }
  return win
}
